﻿using System;
using System.Collections;
using System.Data;
using System.Data;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;
using ACM.cmsarea08.mainconfiguration;
using ACM.cmsarea08.Function.Search;

namespace ACM.cmsarea08.Function
{
	/// <summary>
	/// Description of WebControl1
	/// </summary>

	

	//[ParseChildren(true)]
	//[ProvideProperty("StuffContent", typeof(Control))]
	//[ParseChildren(true, "StuffContent")]	
	public class Searcher 
	{
		/*
		const string baseQuery = ""+
			"(SELECT cod,title,'P' tipo, " +
			"project.lang plang, sys_languages.nome langua, " +
			"cod  prj_cod,title project_name,  match(smalltext,innertext,title) against('{0}' in boolean mode) resulta " +
			"FROM project " +
			" join sys_languages on sys_languages.CultureInfo = project.lang " +
			"where match(smalltext,innertext,title) against('{0}' in boolean mode)>0) " +
			"union " +
			"(SELECT project_news.cod,project_news.title,'D' tipo, " +
			"project_news.lang plang, sys_languages.nome langua, " +
			"codprj as prj_cod,project.title as project_name, match(project_news.title,contents,smcont) against('{0}' in boolean mode) resulta " +
			"FROM project_news left join project on codprj = project.cod " +
			" join sys_languages on sys_languages.CultureInfo = project_news.lang " +
			"where match(project_news.title,contents,smcont) against('{0}' in boolean mode)>0) ";
		*/
		
		public Searcher(string InstanceID){
			_InstID = InstanceID;
		}
		private string _InstID = "";
		const string orderPart = " order by resulta desc limit {0},{1}";
		const string searchContent = " SELECT id,titolo, testo_breve as descrizione, sez_id as idsezione, cast(cat_id as char) as idcategoria, if(managed<>-1," +
			"(SELECT titolo FROM {0}moduli as modu where modu.id = managed)," +
			"'Content Manager') as componente, 'A' as tipo, (match({2})  against('{1}' in boolean mode)) as punti " +
			"FROM {0}contenuti where enabled='1' having punti>0  {3} order by punti desc";
		const string searchContentCount = "(select count(*) as uconteggio,'#contents#' as dove FROM {0}contenuti where enabled='1' and match({2}) against('{1}' in boolean mode)>0) {3} ";
		const string searchCategories = "union (SELECT id,titolo, descrizione,  figliodi as idsezione, cast(id as char) as idcategoria," +
			"if(managed<>-1,(SELECT titolo FROM {0}moduli as modu where modu.id = managed),'Content Manager') as componente, tipo," +
 			"(match(titolo,descrizione) against('{1}' in boolean mode)) as punti "+
			"FROM {0}contenuti_manager where tipo='C' having punti>0 )";
		const string searchCategoriesCount = " union (SELECT count(*) as uconteggio,'#categories#' as dove FROM {0}contenuti_manager where match(titolo,descrizione) " +
			"against('{1}' in boolean mode)>0 and tipo='C') ";
		const string searchSections = "union (SELECT id,titolo, descrizione, id as idsezione,  cast('' as char) as idcategoria," +
			"if(managed<>-1,(SELECT titolo FROM {0}moduli as modu where modu.id = managed),'Content Manager') as componente, tipo," +
 			"(match(titolo,descrizione) against('{1}' in boolean mode)) as punti "+
			"FROM {0}contenuti_manager where tipo='S' having punti>0 )";
		const string searchSectionsCount = " union (SELECT count(*) as uconteggio,'#sections#' as dove FROM {0}contenuti_manager where match(titolo,descrizione) " +
			"against('{1}' in boolean mode)>0 and tipo='S') ";
		
		const string searchComponent = "";
		const string searchComponentCount = "";
		
		string TabPrefix = ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle;
		/*
		const string baseCountQuery = "" + 
			"(SELECT count(*) tot FROM project where match(smalltext,innertext,title) against('{0}' in boolean mode)>0) " +
			"union "+
			"(SELECT count(*) tot FROM project_news where match(project_news.title,contents,smcont) against('{0}' in boolean mode)>0) ";
		*/
		
		const int offSet = 10;
		#region controlli
		private ACM.cmsarea08.DBManager.DBClass dclass = new ACM.cmsarea08.DBManager.DBClass();
		private ACM.cmsarea08.Function.TextClass tClass = new ACM.cmsarea08.Function.TextClass();
		
		public string MasterCont="";
		#endregion
		
		#region proprietà_locali	
		
		#endregion

		#region proprietà_esterne
		private string CurrentSearch;
		private DataSet SearchResult ;
		private int RicercaFilter ;
		private int TotalResult ;
		private int CurrentPage ;	
		
		#endregion
		
		
	
		public string QueryConteggio(SearchParams ricerca, out int count, out string ModuleEmpty){
			count = 0;
			ModuleEmpty = "";
			if(ricerca==null)
				return "";
			string testo = "";
			switch(ricerca.SearchMode){
				
				case TipoRicerca.Frase:
					testo =  "\""+PreparaTesto(ricerca.Testo)+"\"";
					break;
				case TipoRicerca.Ciascuna:
					testo = PreparaTesto(ricerca.Testo);
					break;
				case TipoRicerca.Tutte:
					testo = "+\""+PreparaTesto(ricerca.Testo).Replace(" ","\"+\"")+"\"";
					break;
			}
									
			string campi = "titolo,tag,atitolo";
					if(ricerca.SearchByText)
						campi += ",testo_breve,testo_html";
					if(ricerca.SearchBySections)
						;//campi += "tag,";
					if(ricerca.SearchByCategories)
						;//campi += "tag,";
					
			string queryext = "";
			if(ricerca.SearchBySections)
				queryext += string.Format(searchSectionsCount,TabPrefix,testo);
			if(ricerca.SearchByCategories)
				queryext += string.Format(searchCategoriesCount,TabPrefix,testo);
			string queryconteggio = string.Format(searchContentCount,TabPrefix,testo,campi,queryext);
			
			count = this.EseguiConteggio(queryconteggio, out ModuleEmpty);
			return queryconteggio;
					
			
			return "";
		}
		
		public string QueryConteggio(SearchParams ricerca, string[] IdComponenti, out int count, out string ModuleEmpty){
			count = 0;
			ModuleEmpty = "";
			string testo = "";
			switch(ricerca.SearchMode){
				case TipoRicerca.Frase:
					
					testo =  "\""+PreparaTesto(ricerca.Testo)+"\"";
					break;
				case TipoRicerca.Ciascuna:
					testo = PreparaTesto(ricerca.Testo);
					break;
				case TipoRicerca.Tutte:
					testo = "+\""+PreparaTesto(ricerca.Testo).Replace(" ","\"+\"")+"\"";
					break;
			}
			
			DataRow dr = dclass.Hstandard_ReadRow("select ref_table,campi_table from {0}componenti where id='{1}' ");
			if(dr==null || dr["ref_table"] == null || dr["campi_table"] == null)
				return "";
			
			string campi = dr["campi_table"].ToString();
					
				
			string queryext = "";
			if(ricerca.SearchBySections)
				queryext += string.Format(searchSectionsCount,TabPrefix,testo);
			if(ricerca.SearchByCategories)
				queryext += string.Format(searchCategoriesCount,TabPrefix,testo);
				
					
			return string.Format(searchContentCount,TabPrefix,testo,campi,queryext);
					
			
			return "";
		}
		public string GeneraQuerySelect(SearchParams ricerca){
				string testo = "";
			switch(ricerca.SearchMode){
				case TipoRicerca.Frase:
					
					testo =  "\""+PreparaTesto(ricerca.Testo)+"\"";
					break;
				case TipoRicerca.Ciascuna:
					testo = PreparaTesto(ricerca.Testo);
					break;
				case TipoRicerca.Tutte:
					testo = "+\""+PreparaTesto(ricerca.Testo).Replace(" ","\"+\"")+"\"";
					break;
			}
									
			string campi = "titolo,tag,atitolo";
					if(ricerca.SearchByText)
						campi += ",testo_breve,testo_html";
					if(ricerca.SearchBySections)
						;//campi += "tag,";
					if(ricerca.SearchByCategories)
						;//campi += "tag,";
					
			string queryext = "";
			if(ricerca.SearchBySections)
				queryext += string.Format(searchSections,TabPrefix,testo);
			if(ricerca.SearchByCategories)
				queryext += string.Format(searchCategories,TabPrefix,testo);
				
					
			return string.Format(searchContent,TabPrefix,testo,campi,queryext);
					
			
		}
		
		public string GeneraQuerySelect(SearchParams ricerca, string id_componente, out string ModuleEmpty){
			ModuleEmpty = "";
			return "";
		}
		
		public int EseguiConteggio(string queryconteggio, out string ModuleEmpty){
			ModuleEmpty = "";
			if(queryconteggio.Trim()=="")
				return -1;
			int reso = 0;
			
			try{
				DataSet ds = dclass.Helper_Dataset(queryconteggio);
				if(ds==null)
					return -1;
				
				foreach(DataRow dr in ds.Tables[0].Rows){
					int count = 0;
					count = Convert.ToInt32(dr["uconteggio"]);
					reso+=count;
					if(count==0)
						ModuleEmpty+="," + dr["dove"].ToString();
				}
			}
			catch(Exception ex){
				HttpContext.Current.Response.Write(ex.ToString());
				ModuleEmpty = "";
				reso = -1;
			}
			if(ModuleEmpty.StartsWith(","))
				ModuleEmpty = ModuleEmpty.Substring(1);
			return reso;
		}
		public SearchResults[] EseguiRisultati(string queryselezione){
			//HttpContext.Current.Response.Write(queryselezione);
			System.Collections.Generic.List<SearchResults> risultati = new System.Collections.Generic.List<SearchResults>();
			try{DataSet ds = dclass.Helper_Dataset(queryselezione);
			if(ds==null || ds.Tables.Count==0 || ds.Tables[0].Rows.Count==0)
				return null;
			
			SearchResults[] results = new SearchResults[0];
			int posizione = 0;
			foreach(DataRow dr in ds.Tables[0].Rows){
				SearchResults SR = new SearchResults();
				SR.Titolo = dr["titolo"].ToString();
				SR.Descrizione = dr["descrizione"].ToString();
				string url = "default.aspx";
				
//				HttpContext.Current.Response.Write("SONO : " + dr["idsezione"].GetType() + " , "+
//				                                   dr["idcategoria"].GetType() + "<br/>");
				                                   
//				if(dr["componente"].ToString()=="Content Manager"){
					ACM.cmsarea08.Core.UrlManager.ContentUrlTypes tipo = ACM.cmsarea08.Core.UrlManager.ContentUrlTypes.Content;
					string[] parametri = null;
					if(dr["tipo"].ToString()=="C"){
//						HttpContext.Current.Response.Write("<br>Categoria");
						
						tipo = ACM.cmsarea08.Core.UrlManager.ContentUrlTypes.Category;
						parametri = new string[2] {dr["idsezione"].ToString(),dr["idcategoria"].ToString()};
					}else if(dr["tipo"].ToString()=="S"){
//						HttpContext.Current.Response.Write("<br>Sezione");
						
						tipo = ACM.cmsarea08.Core.UrlManager.ContentUrlTypes.Section;
						parametri = new string[1] {dr["idsezione"].ToString()};
					}else{
//						HttpContext.Current.Response.Write("<br>Articolo");
						
						parametri = new string[3] {dr["idsezione"].ToString(),dr["idcategoria"].ToString(),dr["id"].ToString()};
					}
						
					url = ACM.cmsarea08.Core.UrlManager.GetContentUrl(MainConf.LinguaPredefinita, _InstID,tipo, parametri);
//					HttpContext.Current.Response.Write("<hr>Costruisco l'url con questi dati<br>"+
//					                                   "<br>Tipo: " + dr["tipo"].ToString()+"<br>lingua: "+MainConf.LinguaPredefinita+"<br>idcat :"+dr["idcategoria"].ToString()+
//					                                   "<br>id: "+dr["id"].ToString()+"<br>comp :"+dr["componente"].ToString()+
//					                                   "<br>Url content = \"" + url + "\"<hr>");
//				}else{
//					HttpContext.Current.Response.Write("<br>Managed");
//					
//					url = ACM.cmsarea08.Core.UrlManager.GetUrl(MainConf.LinguaPredefinita, _InstID,dr["id"].ToString()
//						                              					,dr["componente"].ToString());
//					
//					HttpContext.Current.Response.Write("<hr>Costruisco l'url con questi dati<br>"+
//					                                   "<br>Tipo: " + dr["tipo"].ToString()+"<br>lingua: "+MainConf.LinguaPredefinita+"<br>idcat :"+dr["idcategoria"].ToString()+
//					                                   "<br>id: "+dr["id"].ToString()+"<br>comp :"+dr["componente"].ToString()+
//					                                   "<br>Url managed = \"" + url + "\"<hr>");
//					
//				}
				SR.URL = url;
						
				SR.Componente = dr["componente"].ToString();
				//results[posizione] = SR;
				risultati.Add(SR);
				posizione++;	
			}
			}catch(Exception e){
				HttpContext.Current.Response.Write(e.ToString());
			}
			return risultati.ToArray();
		}
		
		public SearchResults[] EseguiRisultati(string queryselezione, bool componente){
			return null;
		}
		
		public string PreparaTesto(string testo){
			
			return PreparaTesto(testo,true);
		}
		public string PreparaTesto(string testo, bool forSQL){
			testo = HttpUtility.HtmlDecode(testo);
			testo = testo.ToLower();
			testo = testo.Trim();
			testo = testo.Replace("\\","");
			testo = tClass.Riduci(testo);
			if(forSQL)
				testo = tClass.SqlTesto(testo);
			
			return testo;
		}
		
	
		
		
		
		
		
	
	}
}
